package com.lehecai.core.task.sender.impl;

import com.lehecai.core.task.IAsyncTask;
import com.lehecai.core.task.dispatcher.IAsyncTaskSenderDispatcher;
import com.lehecai.core.task.entity.AsyncTaskItem;
import com.lehecai.core.task.sender.AbstractAsyncTaskSender;
import com.lehecai.core.task.service.IAsyncTaskService;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by qatang on 14-3-27.
 */
public class CommonAsyncTaskSender extends AbstractAsyncTaskSender {
    private IAsyncTaskSenderDispatcher asyncTaskSenderDispatcher;
    private IAsyncTaskService asyncTaskService;

    protected static ExecutorService executorService = Executors.newCachedThreadPool();

    @Override
    protected void executeSend(AsyncTaskItem asyncTaskItem) {
        final AsyncTaskItem tmpAsyncTaskItem = asyncTaskItem;
        final IAsyncTaskSenderDispatcher tmpAsyncTaskSenderDispatcher = asyncTaskSenderDispatcher;
        //异步执行发送任务
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    tmpAsyncTaskSenderDispatcher.dispatch(tmpAsyncTaskItem);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
    }

    @Override
    protected AsyncTaskItem createTaskData(IAsyncTask asyncTask) throws Exception {
        AsyncTaskItem asyncTaskItem = new AsyncTaskItem();
        asyncTaskItem.setAsyncTask(asyncTask);
        return asyncTaskService.save(asyncTaskItem);
    }

    public IAsyncTaskSenderDispatcher getAsyncTaskSenderDispatcher() {
        return asyncTaskSenderDispatcher;
    }

    public void setAsyncTaskSenderDispatcher(IAsyncTaskSenderDispatcher asyncTaskSenderDispatcher) {
        this.asyncTaskSenderDispatcher = asyncTaskSenderDispatcher;
    }

    public IAsyncTaskService getAsyncTaskService() {
        return asyncTaskService;
    }

    public void setAsyncTaskService(IAsyncTaskService asyncTaskService) {
        this.asyncTaskService = asyncTaskService;
    }
}
